layui.use(['form', 'layer', 'table'], function () {

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;


    /**
     * 备份
     */
    var initExport = function () {
        var exportlist_url = $('.exportlist_url').val();
        var exportpost_url = $('.exportpost_url').val();
        var optimize_url = $('.optimize_url').val();
        var repair_url = $('.repair_url').val();

        var names_arr = new Array();
        // 当前表格中的全部数据:在表格的checkbox全选的时候没有得到数据, 因此用全局存放变量
        var table_data = new Array();

        // export 列表
        var tableExport = table.render({
            elem: '#exportTable',
            url: exportlist_url,
            toolbar: '#exportToolbar', // 开启头部工具栏，并为其绑定左侧模板
            defaultToolbar: ['filter', 'exports', 'print'], // 自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            page: false,
            cellMinWidth: 95,
            //height : "full-100",
            id: "exportList",
            cols: [[
                {type: "checkbox", fixed:"left", width:50},
                {type: 'numbers', title: '序号', width: 80, align: "center"},
                {field: 'Name', title: '表名', minWidth: 200, align: 'center'},
                {field: 'Rows', title: '数据量', align: 'center'},
                {field: 'Data_length', title: '数据大小', align: 'center'},
                {field: 'Collation', title: '编码', align: 'center'},
                {field: 'Create_time', title: '创建时间', minWidth: 180, align: 'center'},
                {field: 'Comment', title: '说明', minWidth: 200, align: 'center'},
                {
                    title: '备份状态', align: "center", fixed:"right", templet: function (data) {
                        var html = '';
                        html += '<input type="hidden" value="'+data.Name+'">';
                        html += '<button class="layui-btn layui-btn-warm layui-btn-xs info">未备份</button>';

                        return html;
                    }
                },
                {
                    title: '操作', fixed: "right", align: "center", minWidth: 160, templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="optimize">优化表</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="repair">修复表</a>';

                        return html;
                    }
                }
            ]],
            done: function(res, curr, count){
                // 设置全部数据到全局变量
                table_data = res.data;
            }
        });

        // 列表操作
        table.on('tool(exportTable)', function (obj) {
            var layEvent = obj.event,
                data = obj.data;

            if (layEvent === 'optimize') {
                // 优化表
                layer.confirm('确定优化此表？', {icon: 3, title: '提示信息'}, function (index) {
                    $.ajax({
                        url: optimize_url,
                        data: {'tables': data.Name},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            layer.close(index);
                            layer.msg(res.info);
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                });
            } else if (layEvent === 'repair') {
                // 修复表
                layer.confirm('确定修复此表？', {icon: 3, title: '提示信息'}, function (index) {
                    $.ajax({
                        url: repair_url,
                        data: {'tables': data.Name},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            layer.close(index);
                            layer.msg(res.info);
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                });
            }
        });

        // 复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
        table.on('checkbox(exportTable)', function (obj) {
            var data = obj.data;
            if (obj.checked == true) {
                if (obj.type == 'one') {
                    // 单选
                    if (names_arr.indexOf(data.Name) < 0) {
                        names_arr.push(data.Name);
                    }
                } else {
                    // 全选 type='all'
                    for (var i = 0; i < table_data.length; i++) {
                        if (names_arr.indexOf(table_data[i].Name) < 0) {
                            names_arr.push(table_data[i].Name);
                        }
                    }
                }
            } else {
                if (obj.type == 'one') {
                    // 单选
                    names_arr.remove(data.Name);
                } else {
                    // 全选 type='all'
                    for (var i = 0; i < table_data.length; i++) {
                        names_arr.remove(table_data[i].Name);
                    }
                }
            }
            console.log(names_arr);
        });

        /**
         * 一键全选
         */
        /*$('.check-all').on('click', function () {
            var check_wrap = $('.check-all'),
                checked = $(this).attr('data-checked'),
                check_items = $('table :checkbox');

            if (checked) {
                check_wrap.html('<i class="layui-icon icon-check layuiadmin-button-btn"></i>&nbsp;全选');
                check_wrap.attr('data-checked', '');

                check_items.removeProp('checked');
                check_items.next().removeClass('layui-form-checked');
            } else {
                check_wrap.text('取消全选');
                check_wrap.attr('data-checked', true);

                check_items.prop('checked', true);
                check_items.next().addClass('layui-form-checked');
            }
        });*/

        var $form = $('#export-form'),
            $export = $('.export-btn'),
            tables = '',
            $optimize = $('.optimize-btn'),
            $repair = $('.repair-btn');

        // 优化表/修复表
        $optimize.add($repair).on('click', function () {
            var _this = $(this);
            // if ($(':checkbox:checked').length <= 0) {
            //     layer.msg('请至少选择一条数据');
            //     return false;
            // }
            //var data = $form.serialize();
            // var checkStatus = table.checkStatus('exportList');
            // var datas = checkStatus.data;
            if (names_arr.length <= 0) {
                layer.msg('请至少选择一条数据！');
                return false;
            }

            var url = _this.attr('data-url');
            var data = {
                'tables': names_arr
            };
            _this.addClass('layui-btn-disabled').prop('disabled', true);
            $.post(url, data, function (res) {
                layer.msg(res.info);
                setTimeout(function () {
                    _this.removeClass('layui-btn-disabled').prop('disabled', false);
                }, 1500);
            }, 'json');
            return false;
        });

        // 备份
        $export.on('click', function () {
            var _this = $(this);
            if (names_arr.length <= 0) {
                layer.msg('请至少选择一条数据！');
                return false;
            }

            var url = exportpost_url;
            var data = {
                'tables': names_arr
            };
            _this.addClass('layui-btn-disabled').prop('disabled', true);
            _this.html('正在发送备份请求...');
            $.post(
                url,
                data,
                function (res) {
                    if (res.code == 1) {
                        tables = res.tables;
                        $export.html(res.info + "开始备份，请不要关闭本页面！");
                        backup(res.tab);
                        window.onbeforeunload = function () {
                            return "正在备份数据库，请不要关闭！";
                        }
                    } else {
                        layer.msg(res.info);
                        $export.html('<i class="layui-icon icon-control-start layuiadmin-button-btn"></i>&nbsp;备份');
                        setTimeout(function () {
                            _this.removeClass('layui-btn-disabled').prop('disabled', false);
                        }, 1500);
                    }
                },
                'json'
            );
            return false;
        });

        // 备份
        function backup(tab, status) {
            status && showMsg(tab.id, "开始备份...(0%)");
            var url = exportpost_url;
            $.get(url, tab, function (res) {
                if (res.code == 1) {
                    showMsg(tab.id, res.info);

                    if (!$.isPlainObject(res.tab)) {
                        $export.removeClass('layui-btn-disabled').prop('disabled', false);
                        $export.html('备份完成，点击重新备份');
                        window.onbeforeunload = function () {
                            return null;
                        };
                        return;
                    }
                    backup(res.tab, tab.id != res.tab.id);
                } else {
                    layer.msg(res.info);
                    $export.html('<i class="layui-icon icon-control-start layuiadmin-button-btn"></i>&nbsp;备份');
                    setTimeout(function () {
                        $export.removeClass('layui-btn-disabled').prop('disabled', false);
                    }, 1500);
                }
            }, 'json');
        }

        function showMsg(id, msg) {
            $form.find("input[value=" + tables[id] + "]").closest('tr').find('.info').removeClass('layui-btn-warm').addClass('layui-btn-normal').html(msg);
        }
    };

    /**
     * 还原
     */
    var initImport = function () {
        var importlist_url = $('.importlist_url').val();
        var importpost_url = $('.importpost_url').val();
        var download_url = $('.download_url').val();
        var delete_url = $('.delete_url').val();

        // import 列表
        var tableImport = table.render({
            elem: '#importTable',
            url: importlist_url,
            page: false,
            cellMinWidth: 95,
            //height : "full-100",
            id: "importList",
            cols: [[
                {type: 'numbers', title: '序号', width: 80, align: "center"},
                {field: 'name', title: '备份文件名称', minWidth: 220, align: 'center'},
                {field: 'part', title: '卷数', width: 80, align: 'center'},
                {field: 'compress', title: '压缩', width: 80, align: 'center'},
                {field: 'size', title: '数据大小', align: 'center'},
                {field: 'mtime', title: '备份时间', minWidth: 160, align: 'center'},
                {title: '状态', align: 'center'},
                {
                    title: '操作', fixed: "right", align: "center", minWidth: 240, templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="download"><i class="layui-icon layui-icon-download-circle"></i>下载</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal import" lay-event="import"><i class="layui-icon layui-icon-return"></i>还原</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                        return html;
                    }
                }
            ]]
        });


        // 列表操作
        table.on('tool(importTable)', function (obj) {
            var layEvent = obj.event,
                data = obj.data;
            var _self = obj.tr.find('.import');

            if (layEvent === 'download') {
                // 下载
                layer.confirm('确定下载此数据？', {icon: 3, title: '提示信息'}, function (index) {
                    download(data.full_filepath);
                    layer.close(index);
                });
            } else if (layEvent === 'import') {
                // 还原数据库
                layer.confirm('确定还原此数据？', {icon: 3, title: '提示信息'}, function (index) {
                    var url = importpost_url + '?time=' + data.time + '&filepath=' + data.filepath;
                    var status = '.';

                    _self.html('<i class="layui-icon layui-icon-return"></i>还原</a>');
                    $.get(url, {}, restore, 'json');
                    window.onbeforeunload = function () {
                        return "正在还原数据库，请不要关闭！"
                    };
                    return false;

                    // 恢复 -- importpost_url 的回调函数
                    function restore(res) {
                        //console.log(res);
                        layer.close(index);
                        if (res.status) {
                            if (res.gz) {
                                res.info += status;
                                if (status.length === 5) {
                                    status = '.';
                                } else {
                                    status += '.';
                                }
                            }
                            _self.text(res.info);
                            if (res.part) {
                                $.get(url,
                                    {'part': res.part, 'start': res.start},
                                    restore,
                                    'json'
                                );
                            } else {
                                window.onbeforeunload = function () {
                                    return null;
                                };
                            }
                        } else {
                            layer.msg(res.info);
                        }
                    }
                });
            } else if (layEvent === 'delete') {
                // 删除
                layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
                    var url = delete_url + '?time=' + data.time;
                    $.ajax({
                        url: url,
                        data: {'filepath': data.filepath},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                layer.msg('已删除', {icon: 1, time: 1000});
                                tableImport.reload();
                                layer.close(index);
                            } else {
                                layer.msg(res.info);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                });
            }
        });

        // 文件下载
        var download = function (src) {
            var $a = document.createElement('a');
            $a.setAttribute("href", src);
            $a.setAttribute("download", "");
            var evObj = document.createEvent('MouseEvents');
            evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
            $a.dispatchEvent(evObj);
        };
    };

    initExport();
    initImport();
});